<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/7
 * Time: 10:12
 */

namespace app\api\controller;

use app\common\model\StateChange;
use app\index\model\ChongZhi;
use app\index\model\ChongzhiList;
use think\Controller;
use think\Db;
use think\response\Json;
header("ACCESS-CONTROL-ALLOW-ORIGIN:http://114.215.68.205");
class Pay extends Controller
{

    private $user;

    public function _initialize()
    {

        parent::_initialize();
        $map = array(
            'username' => input('username', ''),
            'password' => input('password', ''),
            'login_key' => input('login_key', ''),
        );
        $this->user = Db::name('username')->where($map)->where('open', '<', 1)->find();
        //验证加密
        $action = request()->action();
        if( 'payDetail'!=$action  ){
            $VALUE_KEY = ['afewfewfew21342dsaewf'=>'8f4da4f9ew4f98ewq65fwe48f9w'];
            $HEADER_TIME = isset($_SERVER['HTTP_TIME']) ? $_SERVER['HTTP_TIME'] : '';
            $HEADER_KEY = isset($_SERVER['HTTP_KEY']) ? $_SERVER['HTTP_KEY'] : '';
            $HEADER_SIGN = isset($_SERVER['HTTP_SIGN']) ? $_SERVER['HTTP_SIGN'] : '';

            $POST_LOGIN_KEY = isset($_SERVER['HTTP_LOGINKEY']) ? $_SERVER['HTTP_LOGINKEY'] : ( isset($_POST['login_key']) ? $_POST['login_key'] : '' );
            $POST_NAME = isset($_SERVER['HTTP_USERNAME']) ? $_SERVER['HTTP_USERNAME'] : (isset($_POST['username']) ? $_POST['username'] : (isset($_POST['name']) ? $_POST['name']:''));


            if( !isset($VALUE_KEY[$HEADER_KEY]) ){
                exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
            }

            $validation =  $HEADER_TIME.$VALUE_KEY[$HEADER_KEY].$POST_LOGIN_KEY.$POST_NAME;
            if( $HEADER_SIGN != md5($validation) ){
                exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
            }
        }
    }

    public function method()
    {
        $list = Db::name("pay_method")->where(['status' => 1])->field("id,name,logo")->order("seq asc")->paginate()->each(function ($row) {
            $row['logo'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/static/attachment/' . $row['logo'];
            return $row;
        })->toArray();
        $ret = array(
            'result' => 0,
            'datas' => []
        );
        if (!empty($list)) {
            $ret['result'] = 1;
            $ret['datas'] = $list['data'];
        }
        return json_encode($ret, JSON_UNESCAPED_UNICODE);
    }

    public function rechargeList()
    {
        $id = input('id', 0);
        $ret = array(
            'result' => 0,
            'msg' => '无效方案信息',
            'datas' => []
        );
        $method = Db::name('pay_method')->find($id);
        if (empty($method)) {
            $ret['msg'] = '请选中正确支付方案';
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }

        $user = $this->user;
        if (empty($user)) {
            $ret['msg'] = '请先登录账号';
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }
        $level = $user['us_class'];

        //线上第三方
        $onBand = Db::name('pay_type_list')->alias("a")
            ->join("__PAY_XIANSHANG__ b", 'a.method=b.id', 'LEFT')
            ->where(['a.method_id' => $id, 'a.mob' => 1, 'b.open' => 1])
            ->field("a.id,b.pay_name,a.type_name,a.type_value ,b.level,1 as method, 0 as controller")
            ->order('a.order', 'DESC')
            ->select();

        foreach ($onBand as $k => $v) {
            $levelAttr = explode(',', $v['level']);
            $onBand[$k]['controller'] = ChineseToPY($v['pay_name']);
            unset($onBand[$k]['level']);
            if (!in_array($level, $levelAttr)) unset($onBand[$k]);
        }
        //线上支付宝或微信
        $onThird = Db::name("pay_xianshang")->where(['open' => 1, 'is_code' => 1])->field("id,pay_name,level,0 as type_value,2 as method,0 as controller,0 as type_name")->order('order', 'DESC')->select();
        $hasUser = Db::name("code_account")->where(['method_id' => $id,'lock'=>0])->group("type")->column("type,count(*) as num");
        foreach ($onThird as $k => $v) {
            $user_key = $v['pay_name'] == "微信扫码" ? "wechat" : 'alipay';
            if (!isset($hasUser[$user_key]) && empty($hasUser[$user_key])) {
                unset($onThird[$k]);
                continue;
            }
            $levelAttr = explode(',', $v['level']);
            unset($onThird[$k]['level']);
            if (!in_array($level, $levelAttr)) {
                unset($onThird[$k]);
                continue;
            }

        }
        //线下支付
        $offThird = Db::name("pay_xxlist")->where(['method_id' => $id,'status'=>1])->field("id,xx_name as type_name,0 as type_value,xx_weixin,xx_qq,xx_zhifubao,xx_wangyin,3 as method,0 as controller")->select();
        foreach ($offThird as &$v) {
            if (1 == intval($v['xx_weixin'])) $v['pay_name'] = '微信扫码';
            if (1 == intval($v['xx_zhifubao'])) $v['pay_name'] = '支付宝扫码';
            if (1 == intval($v['xx_wangyin'])) $v['pay_name'] = '银联转账';
            if (1 == intval($v['xx_qq'])) $v['pay_name'] = 'QQ扫码';
            unset($v['xx_weixin']);
            unset($v['xx_zhifubao']);
            unset($v['xx_wangyin']);
            unset($v['xx_qq']);
        }
        unset($v);
        $list = array_merge($onBand, $onThird, $offThird);
        if (!empty($list)) {
            $ret['result'] = 1;
            $ret['msg'] = '存在信息';
            $ret['datas'] = $list;
        }
        return json_encode($ret, JSON_UNESCAPED_UNICODE);
    }

    public function detail()
    {
        $method = input('method', 0);
        $ret = array(
            'result' => 0,
            'datas' => []
        );
        if (empty($method)) {
            $ret['msg'] = '参数错误';
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }
        switch ($method) {
            case 1:
                //第三方
                $controller = trim(input('controller', ''));
                if (empty($controller)) {
                    $ret['msg'] = "无效支付方案";
                } else {
                    $username = input('name', '');
                    $type = input('type', '');
                    $amount = input('money', 0);
                    $objname = trim("app\\index\\controller\\Pay{$controller}");
                    $obj = new $objname();
                    /**@var Json $result */
                    $result = $obj->initPay($username, $type, $amount, 1);
                    $data = $result->getData();
                    $status = $data['status'];
                    if (200 == $status) {
                        $ret['result'] = 1;
                        $ret['msg'] = '有可用信息';
                        $val['content'] = $data['data'];
                        $val['type'] = 0; // 0:URL;1:HTML;2:图片;3:加密信息
                        $ret['datas'] = $val;
                    } elseif (201 == $status) {
                        $ret['result'] = 1;
                        $ret['msg'] = '有可用信息';
                        $val['content'] = $data['data'];
                        $val['type'] = 1;
                        $ret['datas'] = $val;
                    }elseif( 202 == $status){
                        $ret['result'] = 1;
                        $ret['msg'] =  '有可用信息';
                        $val['content'] = $data['data'];
                        $val['type'] = 2;
                        $ret['datas'] = $val;
                    }elseif( 203==$status ){
                        $ret['result'] = 1;
                        $ret['msg'] = '有可用信息';
                        $val['content'] = $data['data'];
                        $val['type'] = 3; 
                        $ret['datas'] = $val;
                    } else {
                        $ret['result'] = 0;
                        $ret['msg'] = $data['info'];
                    }
                }
                break;
            case 2:
                //线上
                $money = input('money', 0);
                $type = input('type', 0);  //wechat,alipay
                $info = self::buildCode($this->user, $money, $type);
                $infoAttr = json_decode($info, true);
                $status = $infoAttr['status'];
                if (500 == $status) {
                    //失败
                    $ret['msg'] = $infoAttr['info'];
                } else {
                    $ret['result'] = 1;
                    $ret['msg'] = '存在可用二维码';
                    $ret['datas'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/uploads/code/' . $infoAttr['data']['code'];
                }
                break;
            case 3:
                //线下
                $id = input('id', 0);
                $detail = Db::name("pay_xxlist")->field("xx_name,xx_weixin,xx_zhifubao,xx_wangyin,xx_qq,xx_test,xx_bankname,xx_bankno,xx_bankren,xx_erweima,xx_remark")->find($id);
                if (!empty($detail)) {
                    $detail['xx_erweima'] = !empty($detail['xx_erweima']) ? $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/static/attachment/' . $detail['xx_erweima'] : '';
                    if (1 == intval($detail['xx_weixin'])) {
                        $detail['type'] = 1;
                    } elseif (1 == intval($detail['xx_zhifubao'])) {
                        $detail['type'] = 2;
                    } elseif (1 == intval($detail['xx_qq'])) {
                        $detail['type'] = 4;
                    } else {
                        $detail['type'] = 3;
                    }
                    unset($detail['xx_weixin']);
                    unset($detail['xx_zhifubao']);
                    unset($detail['xx_wangyin']);
                    unset($detail['xx_qq']);
                    $ret['result'] = 1;
                    $ret['msg'] = '存在可用支付信息';
                    $ret['datas'] = $detail;
                } else {
                    $ret['msg'] = '支付方案不存在';
                }
                break;
            default:
        }
        return json_encode($ret, JSON_UNESCAPED_UNICODE);
    }

    public function apply(){

        $user = $this->user;
        $ret = array(
            'result' => 0,
            'msg' => ''
        );
        if (!$user) {
            $ret['msg'] = '请重新登录';
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }
        //开始处理充值
        if (intval($user['swzh']) == 1) {
            $ret['msg'] = '试玩账号无法充值';
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }
        $type = input('post.type', 0);  //1:微信；2：支付宝：3：银行
        if (empty($type)) {
            $ret['msg'] = '支付方案错误，请重新选择';
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }
        $money = floatval(input('post.money', 0));//金钱
        if ($money <= 0) {
            $ret['msg'] = '请输入正确金额';
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }

        //内部账户
        if (intval($user['nbzh']) > 0) {
            $state = new StateChange();
            $where = array('username' => $user['username'], 'nbzh' => 1);
            $state->SaveRecharge('username', $where, array('je' => floatval($user['je']) + $money, 'czzje' => floatval($user['czzje']) + $money));
            $ret['msg'] = '提交成功';
            $ret['result'] = 1;
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        } else {
            //判断防骚扰
           
            $count_sheuid = Db::name('xt_czfsr')->find();
            if ($count_sheuid['open'] > 0) {
                $nowys = time() - $count_sheuid['time_xx'] * 60;
                $old_czjl = Db::name('chongzhi_list')->where('username', $user['username'])->where('cztime', '>', $nowys)->find();
                if (!empty($old_czjl)) {
                    return json_encode(['result' => 0, 'msg' => "系统充值防骚扰已开启，{$count_sheuid['time_xx']}分钟内只能充值1次！"]);
                }
            }
           
            //会员等级与百分比
            $ts = Db::name('us_class')->where('id', $user['us_class'])->find();
            $usclass = '';
            $hyzsbs = 0;
            if (!empty($ts)) {
                $usclass = $ts['id'];
                $hyzsbs = $ts['czzsbl'];
            }
            
            //判断单次充值是否满一定金额，达到赠送金额；
            $xtcz = Db::name('xt_chongzhi')->where('id', 1)->find();
            $xxczje = 0;
            $xxczzsbs = 0;
            if (!empty($xtcz)) {
                $xxczje = $xtcz['xxcz_je'];
                $xxczzsbs = $xtcz['xxcz_zs'];;
            }
            $liuyan = input('post.remark', '');      //备注信息
            if (empty($liuyan)) {
                $ret['msg'] = '请输入验证信息';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
            $enter_time = input('post.time', '');    //充值
            if (empty($enter_time)) {
                $ret['msg'] = '请选择存入时间';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
            //提交充值
            $time = strtotime($enter_time);
            $account_id = input('post.account', 0);  //账号
            if (empty($account_id)) {
                $ret['msg'] = '请选择充值账户';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
            $account = Db::name('pay_xxlist')->field("xx_bankren,method_id,label")->where('id',$account_id)->find();
            $ddbh = $account['label'] . $time . rand(0, 999);

            $method = Db::name('pay_method')->find($account['method_id']);
            $method_money = 0.00;
            if( floatval( $method['money'] ) > 0 ){
                if( 0==intval( $method['method'] ) ){
                    //金额
                    $method_money = $method['money'];
                }else{
                    //比例
                    $method_money = floatval($money) * floatval($method['money']) / 100;
                }
            }
            
            $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));
            $xxbank = '';
            switch (intval($type)) {
                case 1:
                    $xxbank = '微信转账';
                    break;
                case 2:
                    $xxbank = '支付宝转账';
                    break;
                case 3:
                    $xxbank = '网银转账';
                    break;
                case 4:
                    $xxbank = 'QQ转账';
                    break;
            }
            $czadmin = '';
            $czclass = 2;
            $msje = 0;
            $msbs = 0;
            if ($money >= $xxczje) {
                $msje = $money * $xxczzsbs / 100;
                $msbs = $xxczzsbs;
            }
            $zsbs = $hyzsbs;
            $zsje = $money * $hyzsbs / 100;
            $chongzhi = new ChongZhi();
            
            if ($chongzhi->WeiXinRecharge($czadmin, $ddbh, $money, $user['username'], '0', '0', $czclass, $xxbank, $time, get_ip(), '0', $liuyan, $zsje, $zsbs, $msje, $msbs, $usclass, $account['xx_bankren'],$method_money,$user['je'])) {
            	$ret['msg'] = '提交成功';
                $ret['result'] = 1;
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            } else {
                $ret['msg'] = '充值失败';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
        }
    }
    public function payDetail(){
        $this->assign('image',base64_decode(input('img','')));
        $this->assign('money',input('money',0.00));
        $url = base64_decode(input('url',''));
        $this->assign('url',$url);
        //echo $url;
        return $this->fetch('pay_detail');
    }
    private static function buildCode($user_info, $money, $pay_type){

        Db::startTrans();
        //接收数据
        $username = input('post.username', '');
        $username = strtolower($username);
        if (!$user_info) return self::packJson('', '用户身份验证失败', 500);
        if ($user_info['swzh'] == 1) return self::packJson('', '试玩账号无法充值', 500);
        if ($user_info['nbzh'] == 1) return self::packJson('', '内部账号不支持线上充值', 500);
        //验证金额
        if ($money <= 0) return self::packJson('', '输入的金额无效', 500);
        if (!in_array($pay_type, ['wechat', 'alipay'])) return self::packJson('', '无效的充值方式', 500);

        if( 'wechat'==$pay_type ){
            $remark = '微信二维码转账';
        }else{
            $remark = '支付宝二维码转账';
        }

        //生成订单号
        try {
            $online_ac = Db::name('code_account')->alias('ca')
                ->join('__RESPONSE_CODE__ rc', 'rc.account=ca.id')
                ->where(['ca.type' => $pay_type, 'ca.lock' => 0, 'ca.status' => 0, 'rc.status' => 1, 'rc.region' => $money])
                ->limit(1)
                ->find();
            if (empty($online_ac)) return self::packJson('', '当前支付人数过多请稍后重试', 500);
            $order_sn = $online_ac['label'] . str_pad($user_info['id'], 10, '0', STR_PAD_LEFT) . time() . rand(111, 999);

            Db::name('response_code')->where('id', $online_ac['id'])->update(['status' => 0, 'remark' => $order_sn]);
            $code = Db::name('response_code')->alias('rc')
                ->field('rc.*,ca.name,ca.max_je')
                ->join('__CODE_ACCOUNT__ ca', 'ca.id=rc.account')
                ->where('rc.id', $online_ac['id'])
                ->find();
            if (empty($code)) return self::packJson('', '当前支付人数过多请稍后重试', 500);

            $method = Db::name('pay_method')->find($online_ac['method_id']);
            $method_money = 0.00;
            if( !empty($method) && floatval($method['money']) > 0 ){
                if( 0==intval( $method['method'] ) ){
                    //金额
                    $method_money = $method['money'];
                }else{
                    //比例
                    $method_money = floatval($money) * floatval($method['money']) / 100;
                }
            }
            $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));
            $je = floatval($code['max_je']) - floatval($code['money']);
            Db::name('code_account')->where('id', $code['account'])->update(['max_je' => $je]);
            if ($code['max_je'] <= $money) {
                if ($pay_type == 'wechat') return self::packJson('', '微信充值已达最大限额，请更换其他方式充值', 500);
                if ($pay_type == 'alipay') return self::packJson('', '支付宝充值已达最大限额，请更换其他方式充值', 500);
            }
            //充值防骚扰是否开启，并进行处理
            $harassment = Db::name('xt_czfsr')->find();
            if (!empty($harassment) && $harassment['open'] > 0) {
                $nowys = time() - $harassment['time_xs'] * 60;
                $old_czjl = Db::name('chongzhi_list')->where('username', $username)->where('cztime', '>', $nowys)->find();
                if ($old_czjl && $old_czjl['id'] > 0) {
                    return self::packJson('', "系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！", 500);
                }
            }
            //计算优惠金额
            $msje = $msbs = 0;
            $cz_set = Db::name('xt_chongzhi')->find();
            $user_class = Db::name('us_class')->where('id', $user_info['us_class'])->find();
            $zsje = $code['money'] * $user_class['czzsbl'] / 100;
            $zsbs = $user_class['czzsbl'];
            if ($money >= $cz_set['xscz_je']) {
                $msje = $code['money'] * $cz_set['xscz_zs'] / 100;
                $msbs = $cz_set['xscz_zs'];
            }
            //插入充值信息
            $u = Db::name('username')->where('username',$username)->value('je');
            $model = new ChongzhiList();
            $model->setTransRechargeInfo($order_sn, $code['money'], $username, 0, 0, 1, $remark, time(), $code['name'], '二维码回调', get_ip(), 0, $pay_type, $zsje, $zsbs, $msje, $msbs, $user_info['us_class'],'',1,$method_money,$u);
            Db::commit();
            return self::packJson($code, '', 200);
        } catch (\Exception $e) {
            Db::rollback();;
            return self::packJson('', '生成失败请重试', 500);
        }
    }

    private static function packJson($data = '', $info = '', $status = 500)
    {
        $res = array(
            'data' => $data,
            'info' => $info,
            'status' => $status
        );
        return json_encode($res);
    }

}